<template>
    <button
        :type="metadata.options.isDanger?'warn':metadata.options.type"
        :plain="metadata.options.isGhost"
        size="mini"
        :disabled="disabledShow"
        @click="handleClick">
        {{ $i18(metadata.name) }}
    </button>
</template>

<script>
/*
按钮控件
 */
import MForm from '../js/MForm'
import Dialog from "@/js/Dialog";
import FormBoListPreview from "@/views/modules/form/formBoList/FormBoListPreview.vue";
import FormConstant from "../../../../js/FormConstant";
import baseButtonFunc from "@/js/baseButtonFunc.js"
export default {
    name: "MButton",
    mixins: [MForm,baseButtonFunc],
    components: {
        FormBoListPreview
    },
    data() {
        return {
            dialogalias: "",
            params: '',
        }
    },
    computed:{
        disabledShow(){
            if(this.metadata.control.editable){
                return false
            }
            if(this.metadata.control.editCondition && this.metadata.control.editCondition.condition){
                let hasShow = false ;
                let { condition} = this.metadata.control.editCondition;
                if(condition.indexOf('return') === -1){
                    condition = 'return ' + condition;
                }
                let fn = new Function('row','data',condition).call(this.formVm,this.data);
                hasShow = fn
                return !hasShow ;
            }
            return  this.showButton() || this.readOnly
        },
        showButton(){
            let self = this ;
            return ()=>{
                let hasShow = false ;
                if(this.metadata.control && this.metadata.control.disableConditions){
                    let { condition} = this.metadata.control.disableConditions;
                    if(condition.indexOf('return') === -1){
                        condition = 'return ' + condition;
                    }
                    let fn = new Function('row','data',condition).call(this.formVm,this.data);
                    hasShow = fn
                }
                return hasShow ;
            }
        }
    },
    methods: {
        handleClick(e) {
            let {eventType, methodName} = this.metadata.control;
            if (eventType === 'method') {
                //执行自定义方法
                var parent = this.formVm;
                parent[methodName]();
            } else {
                //执行自定义对话框
                this.handDialog();
            }
        },
        handDialog() {
            if (!this.metadata.options.dialogConfig) {
                return;
            }
            let dialogConfig = JSON.parse(this.metadata.options.dialogConfig);
            if(dialogConfig.beforeMethod && this.isBeforeMethod(dialogConfig.beforeMethod)){
                return;
            }
            if (!dialogConfig.dialogAlias) {
                uni.showToast({
                    title: this.i18n('boundDialog', '没有绑定对话框'), // 消息内容
                    duration: 1500, // 持续时间（单位：毫秒）
                    icon: 'none' // 图标类型（可选值：success/loading/none）
                });
                return;
            }
            let dialogAlias = JSON.parse(dialogConfig.dialogAlias).value;
            let gridInput = dialogConfig.gridInput;
            /*如果输入条件有必填，则提示*/
            if(this.isConditionRequired(gridInput,this.formVm.data,this.data)){
                return;
            }

            //单多选
            this.single = dialogConfig.singleType == 'single';
            //构建查询条件。
            var params = this.getDialogParams(gridInput, this.globalData, this.data);
            params = Object.keys(params).map(function (key) {
                return key+ "=" +params[key];
            }).join("&");

            let self_ = this;

            let conf = {
                data: {
                    alias: dialogAlias,
                    single: this.single,
                    params: params,
                },
                curVm: this,
            };
            Dialog.openDialog(conf, function (data) {
                if (data.action == "ok") {
                    self_.setDialogData(data.data.rows);
                    let eventConfig = JSON.parse(self_.metadata.options.dialogConfig);
                    if (eventConfig.callback) {
                        self_.formVm[eventConfig.callback]({rows: data.data.rows});
                    }
                }
            })
        },

        /**
         * 设置数据
         */
        setDialogData(rows) {
            let binding = JSON.parse(this.metadata.options.dialogConfig);
            var self_ = this;
            var gridName = binding.gridName;
            var superaddition = binding.superaddition;
            var returnFields = binding.returnFields;
            var textField = binding.textField;
            var valueField = binding.valueField;

            let table = FormConstant.SubPrefix + gridName;
            for (var i = 0; i < rows.length; i++) {
                var rtnTmp = rows[i];
                //子表对象
                var subObj = {};

                for (var k = 0, l = returnFields.length; k < l; k++) {
                    var item = returnFields[k];
                    var returnField = item.returnValue; //返回字段
                    var bindField = item.bindField //绑定字段
                    //绑定字端没有就退出
                    if (!bindField) {
                        continue
                    }
                    //主表编辑按钮  绑定主表值
                    var val = rtnTmp[returnField];
                    if (item.isMultiLang) {
                        val = this.$i18(val);
                    }
                    if (gridName == 'curForm') {
                        this.$set(self_.data, bindField, val)
                    } else if (gridName != 'curForm') { //一对一子表
                        if (self_.data[table] && self_.data[table].length == undefined) {
                            self_.$set(self_.data[table], bindField, val)
                        } else {
                            subObj[bindField] = val;
                        }
                    }
                }
                if (gridName && self_.data[table] && self_.data[table].length != undefined) {
                    let uniqueField = binding.uniqueField;
                    let subTableData = this.getSubData(gridName);
                    //子表
                    if (!superaddition) {
                        //是否追加，不是就先清空
                        self_.data[table] = [];
                        self_.data[table].push(subObj)
                    } else {
                        let canAdd = this.canAddRow(uniqueField, subObj, subTableData);
                        if (canAdd) {
                            self_.data[table].push(subObj)
                        }
                    }
                }
            }
        },
        getDialogParams(gridInput, data, row) {
            if (!gridInput || gridInput.length == 0) return {};
            var param = {};
            for (let i = 0, j = gridInput.length; i < j; i++) {
                var obj = gridInput[i];
                var bindVal = obj.bindVal;
                if (!bindVal) {
                    continue;
                }
                var valMode = obj.valMode;
                var table = obj.table;
                var mode = obj.mappingMode;
                var val = "";
                if (mode == "mapping") {
                    val = "main" == table || "curForm" == table ? data[bindVal] : row[bindVal]
                } else {
                    //脚本方式
                    let func = new Function("data", "row", "mainTable", bindVal);
                    let mainTable = true;
                    if (table != "main") {
                        mainTable = false;
                    }
                    /*
                    *参数：
                    * data:表单数据
                    * row: 行数据
                    * mainTable：是否主表
                     */
                    val = func(data, row, mainTable);
                }
                let paramVal = "";
                if (val) {
                    if (mode == "mapping") {
                        if (valMode == "single" && obj.ctlType != "buttonEditSingle") {
                            paramVal = val;
                        } else {
                            let json = JSON.parse(val)
                            paramVal = json.value;
                        }
                    } else {
                        paramVal = val;
                    }
                }
                if (!paramVal) { //父联动字段为空
                    delete param[obj.field];
                } else {
                    param[obj.field] = paramVal;
                }
            }
            return param;
        },
    },

}
</script>

<style scoped>
.rx-popup {
    position: fixed;
    top: 0px;
    bottom: 0px;
    z-index: 99;
    left: 0px;
    right: 0px;
    background: white;
    z-index: 9999;
}
</style>
